package com.xauto.pioneer.appuser.activity.takeCar;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.TextView;

import com.mylhyl.acp.Acp;
import com.mylhyl.acp.AcpListener;
import com.mylhyl.acp.AcpOptions;
import com.xauto.pioneer.appuser.R;
import com.xauto.pioneer.appuser.activity.BaseActivity;
import com.xauto.pioneer.appuser.adapter.ImageSelectAdapter;
import com.xauto.pioneer.appuser.http.BaseLHttpHandler;
import com.xauto.pioneer.appuser.http.Constants;
import com.xauto.pioneer.appuser.http.LHttpLib;
import com.xauto.pioneer.appuser.interfaces.WebInfoCallBack;
import com.xauto.pioneer.appuser.model.DamageImageInfo;
import com.xauto.pioneer.appuser.model.Image;
import com.xauto.pioneer.appuser.model.JSONStatus;
import com.xauto.pioneer.appuser.model.WebInfo;
import com.xauto.pioneer.appuser.util.DataLoadUtil;
import com.xauto.pioneer.appuser.util.ToastUtil;
import com.xauto.pioneer.appuser.view.ImageSelectDialog;
import com.xauto.pioneer.appuser.view.TopBar;
import com.yongchun.library.model.LocalMedia;
import com.yongchun.library.view.ImagePreviewActivity;
import com.yongchun.library.view.ImageSelectorActivity;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * 车辆拍照界面
 * Created by Ellis.Li on 2017/5/17.
 */

public class TakeCarPhotoActivity extends BaseActivity implements AdapterView.OnItemClickListener {
    @Bind(R.id.topBar)
    TopBar topBar;
    @Bind(R.id.noScrollgridview)
    GridView noScrollgridview;
    @Bind(R.id.take_car_text)
    TextView takeCarText;
    @Bind(R.id.webView)
    WebView webView;
    ImageSelectAdapter imageSelectAdapter;
    private List<LocalMedia> selectedPhotos = new ArrayList<>();
    private List<LocalMedia> updatePhotos;
    private List<DamageImageInfo> updateServerPhotos;
    private ImageSelectDialog imageSelectDialog;
    Uri imageUri;
    //车辆编号
    String carNo = "";
    String longitude = "",latitude = "",address = "";

    @Override
    protected int getContentView() {
        return R.layout.ac_take_photo_feedback;
    }

    @Override
    protected void initView() {
        topBar.showView(TopBar.TITLE, TopBar.LEFT_IMAGE_BTN);
        topBar.setText(TopBar.TITLE, "取车拍照");
        topBar.setImage(TopBar.LEFT_IMAGE_BTN, R.mipmap.ic_common_left);
        topBar.setLeftOnClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
    }

    @Override
    protected void initData() {
        carNo = getIntent().getStringExtra("car_no");
        longitude = getIntent().getStringExtra("longitude");
        latitude = getIntent().getStringExtra("latitude");
        address = getIntent().getStringExtra("address");
        imageSelectAdapter = new ImageSelectAdapter(this, R.layout.item_photo);
        selectedPhotos.add(new LocalMedia(""));
        imageSelectAdapter.getDataList().clear();
        imageSelectAdapter.getDataList().addAll(selectedPhotos);
        imageSelectAdapter.notifyDataSetChanged();
        noScrollgridview.setAdapter(imageSelectAdapter);
        noScrollgridview.setOnItemClickListener(this);
        getCarDamageList();
    }


    @OnClick(R.id.take_car_text)
    public void onViewClicked() {
        //确定用车 先上传图片 后调取用车接口
        updatePhotos = selectedPhotos;
        //数组先去掉添加完成按钮
        updatePhotos.remove(updatePhotos.size()-1);
        updateServerPhotos = new ArrayList<>();
        updateImages();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (imageSelectAdapter.getCount() <= 10) {
            if (position == imageSelectAdapter.getCount() - 1){
                //打开拍照或者相册先校验权限问题
                Acp.getInstance(this).request(new AcpOptions.Builder()
                                .setPermissions(Manifest.permission.WRITE_EXTERNAL_STORAGE
                                        , Manifest.permission.READ_PHONE_STATE
                                        , Manifest.permission.SEND_SMS)
                /*以下为自定义提示语、按钮文字
                .setDeniedMessage()
                .setDeniedCloseBtn()
                .setDeniedSettingBtn()
                .setRationalMessage()
                .setRationalBtn()*/
                                .build(),
                        new AcpListener() {
                            @Override
                            public void onGranted() {
                                showPhotoDialog();
                            }

                            @Override
                            public void onDenied(List<String> permissions) {
                                prompt(permissions.toString() + "权限拒绝");
                            }
                        });
            }else {
                //预览图片
                List<LocalMedia> previewPhotos = selectedPhotos;
                previewPhotos.remove(previewPhotos.size()-1);
                ImagePreviewActivity.startPreview(this, previewPhotos, previewPhotos, Constants.MAX_SELECT_NUM, position);
            }
        } else {
           prompt("最多添加"+Constants.MAX_SELECT_NUM+"张图片");
        }
    }
    /**
     * 废弃
     * 请求访问权限
     */
    public void showPhotoDialogPremission(){
        if (Build.VERSION.SDK_INT>=23){
            if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.READ_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED
                    || ActivityCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA)
                    != PackageManager.PERMISSION_GRANTED) {
                ToastUtil.showShort(mContext,"没有权限,请手动开启定位权限");
                // 申请一个（或多个）权限，并提供用于回调返回的获取码（用户定义）
                ActivityCompat.requestPermissions(TakeCarPhotoActivity.this,new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE, android.Manifest.permission.CAMERA}, 100);
            }else{
                showPhotoDialog();
            }
        }else{
            showPhotoDialog();
        }
    }
    //Android6.0申请权限的回调方法
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            // requestCode即所声明的权限获取码，在checkSelfPermission时传入
            case 100:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 获取到权限，作相应处理（调用定位SDK应当确保相关权限均被授权，否则可能引起定位失败）
                    showPhotoDialog();
                } else {
                    // 没有获取到权限，做特殊处理
                    ToastUtil.showShort(mContext,"获取位置权限失败，请手动开启");
                }
                break;
            default:
                break;
        }
    }
    /**
     * 显示选择相册弹出框
     */
    private void showPhotoDialog() {
        if (imageSelectAdapter.getCount() >= 10) {
            prompt("最多添加"+"9张图片");
            return;
        }
        if (imageSelectDialog != null) imageSelectDialog = null;
        imageSelectDialog = new ImageSelectDialog(mContext, new ImageSelectDialog.ImageSelectCallBack() {
            @Override
            public void takePhoto() {
                imageUri = Uri.parse("file:///sdcard/IMG_" + +System.currentTimeMillis() + ".jpg");
                Intent intent = new Intent(
                        MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri
                );
                try {

                    startActivityForResult(intent,
                            100);
                } catch (Exception e) {

                }
            }

            @Override
            public void selectPhotos() {
                List<LocalMedia> photos = selectedPhotos;
                photos.remove(photos.size()-1);
                ImageSelectorActivity.start(TakeCarPhotoActivity.this, Constants.MAX_SELECT_NUM, ImageSelectorActivity.MODE_MULTIPLE, false, true, true,photos);
            }
        });
        imageSelectDialog.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != Activity.RESULT_OK) { //result is not correct
            Log.e(TAG, "requestCode = " + requestCode);
            Log.e(TAG, "resultCode = " + resultCode);
            Log.e(TAG, "data = " + data);
            return;
        } else {
            switch (requestCode) {
                case 100:
                    cropImageUri(imageUri, 101);
                    break;
                case 101:
                    imageSelectAdapter.getDataList().clear();
                    selectedPhotos.remove(selectedPhotos.size()-1);
                    selectedPhotos.add(new LocalMedia(imageUri.getPath()));
                    selectedPhotos.add(new LocalMedia(""));
                    imageSelectAdapter.getDataList().addAll(selectedPhotos);
                    imageSelectAdapter.notifyDataSetChanged();
                    break;
                case ImageSelectorActivity.REQUEST_IMAGE:
                    imageSelectAdapter.getDataList().clear();
                    selectedPhotos = (List<LocalMedia>) data.getSerializableExtra(ImageSelectorActivity.REQUEST_OUTPUT);
                    selectedPhotos.add(new LocalMedia(""));
                    imageSelectAdapter.getDataList().addAll(selectedPhotos);
                    imageSelectAdapter.notifyDataSetChanged();
                    break;
            }
        }
    }

    private void cropImageUri(Uri uri, int requestCode) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 360);
        intent.putExtra("outputY", 360);
        intent.putExtra("scale", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        intent.putExtra("return-data", false);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true); // no face detection
        startActivityForResult(intent, requestCode);
    }

    /**
     *上传图片
     */
    private void updateImages() {
        if (updatePhotos == null || updatePhotos.size() == 0){
            //所有图片上传成功
            if (updateServerPhotos != null){
                for (int i=0,size = updateServerPhotos.size();i<size;i++){
                    Log.d(TAG,"server source: "+updateServerPhotos.get(i).getDamage_image());
                }
            }
            Intent intent = new Intent();
            intent.putExtra("updateServerPhotos",(Serializable) updateServerPhotos);
            setResult(RESULT_OK,intent);
            finish();
            return;
        }
        String currentImgLocalPath = updatePhotos.get(0).getPath();
        new LHttpLib().editImage(mContext, memberId, Constants.IMAGE_TYPE_DAMAGE_ID, currentImgLocalPath, new BaseLHttpHandler(mContext, true, true) {
            @Override
            public void onSuccess(JSONStatus jsonStatus) {
                super.onSuccess(jsonStatus);
                final Image image = new Image().parse(jsonStatus.data.optJSONObject("image_info"));
                DamageImageInfo damageImageInfo = new DamageImageInfo(image.source,System.currentTimeMillis(),address,latitude,longitude);
                updateServerPhotos.add(damageImageInfo);
                updatePhotos.remove(0);
                updateImages();
            }
        });
    }

    /**
     * 获取车辆损伤列表
     */
    private void getCarDamageList(){
        DataLoadUtil.getWebInfo(mContext, "9", "", carNo, new WebInfoCallBack() {
            @Override
            public void getWebInfo(WebInfo webInfo) {
                if ("1".equals(webInfo.data_type)) {
                webView.loadUrl(webInfo.data_value.content);
            } else {
                webView.loadData(webInfo.data_value.content, "text/html; charset=UTF-8", null);//这种写法可以正确解码
            }
            }
        });
//        new LHttpLib().getCarDamageList(mContext, memberId,carNo, new BaseLHttpHandler(mContext, true, true) {
//            @Override
//            public void onSuccess(JSONStatus jsonStatus) {
//                super.onSuccess(jsonStatus);
//                JSONArray car_damage_list = jsonStatus.data.optJSONArray("car_damage_list");
//                if (car_damage_list != null){
//                    List<CarDamageInfo> damageList = new ArrayList<>();
//                    int length = car_damage_list.length();
//                    for (int i=0;i<length;i++){
//                        CarDamageInfo carDamageInfo = new CarDamageInfo().parse(car_damage_list.optJSONObject(i));
//                        damageList.add(carDamageInfo);
//                        //显示损伤信息
//
//                    }
//                }
//            }
//        });
    }
}
